<?php

namespace app\task\command\power;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Db;

/**
 * 微客云电费充值
 */
class Wikeyun extends Command
{
    /**
     * 配置指令.
     */
    protected function configure()
    {
        $this->setName('power:wikeyunCreateOrder')
            ->setDescription('Create wikeyun power order');
    }

    /**
     * 执行指令.
     */
    protected function execute(Input $input, Output $output)
    {
        echo '开始微客云电费下单'.PHP_EOL;
        $lockKey = 'wikeyun_power_order_lock_key';
        $lockVal = cache($lockKey);
        if ($lockVal) {
            echo '还在处理呢'.PHP_EOL;

            return true;
        }

        cache($lockKey, 1, 120);

        $api = Db::name('base_supplier')
            ->where('code', 'wikeyun')
            ->where('serv_type', PRODUCT_POWER_SERV)
            ->whereNull('deleted_at')
            ->find();
        if (empty($api)) {
            echo '微客云接口配置有误';
            cache($lockKey, null);

            return false;
        }

        // 账户余额小于 200，不跑了
        // if ($api['balance'] < 20000) {
        //     echo '微客云账户余额不足了'.PHP_EOL;

        //     return false;
        // }

        $where = [];
        $where[] = ['status', '=', 2];
        $where[] = ['supplier_status', '=', 1];
        $where[] = ['supplier_id', '=', $api['id']];

        $list = Db::name('power_order')
            ->where($where)
            ->limit(100)
            ->order('updated_at asc')
            ->select()
            ->toArray();
        $model = new \api\power\Wikeyun($api);
        $done = 0;
        $now = time();
        foreach ($list as $v) {
            $res = $model->create($v);
            if (!isset($res['code']) || $res['code'] == '1009') {
                echo json_encode($res, JSON_UNESCAPED_UNICODE).PHP_EOL;
                continue;
            }

            // 余额不足，不再下单
            // if ($res['code'] == '1008') {
            //     Db::name('power_order')
            //         ->where('id', $v['id'])
            //         ->update([
            //             'remark' => $res['msg'] ?? '余额不足',
            //         ]);
            //     break;
            // }

            if ($res['code'] == '0000') {
                ++$done;
                $update = [
                    'supplier_status' => 2,
                    'supplier_order_no' => $res['data']['order_number'],
                    'supplier_order_create_time' => $now,
                    'remark' => '',
                ];
            } else {
                $update = [
                    'supplier_status' => 4,
                    'refund_status' => 2,
                    'finish_time' => time(),
                    'remark' => $res['msg'] ?? '下单失败',
                ];
            }

            Db::name('power_order')
                ->where('id', $v['id'])
                ->update($update);
        }

        $balance = $model->queryAmount();
        if ($balance !== false) {
            Db::name('base_supplier')
                ->where('id', $api['id'])
                ->update([
                    'balance' => $balance,
                ]);
        }

        cache($lockKey, null);

        echo '微客云电费下单结束。成功下了 '.$done.' 单'.PHP_EOL;
    }
}
